package com.loveprogrammer.factory;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.loveprogrammer.factory.template.MapTemplate;
import com.loveprogrammer.model.battle.MonsterInMap;
import com.loveprogrammer.model.battle.TownMap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @description: 地图工厂
 * @author: eric
 * @date: 2022-08-08 16:44
 **/
public class MapFactory {

    private static List<MapTemplate> mapTemplates;

    private static Map<String,MapTemplate> templateMap;

    // 初始化地图模版
    static {
        try {
            // 读取配置文件，然后加载到weaponTemplates中
            ClassLoader classLoader = MapFactory.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("template/map.json");

            assert inputStream != null;
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            mapTemplates = JSONArray.parseArray(responseStrBuilder.toString(), MapTemplate.class);

            templateMap = mapTemplates.stream().collect(Collectors.toMap(MapTemplate::getId, e->e));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<MapTemplate> mapTemplates() {
        return mapTemplates;
    }

    public static MapTemplate getMapById(String templateId) {
       return templateMap.get(templateId);
    }

    public static TownMap createMap(MapTemplate mapTemplate) {
        return new TownMap(mapTemplate);
    }

    // 生成地图中的野怪
    public static List<MonsterInMap> createMonsters(MapTemplate mapTemplate) {
        List<MonsterInMap> result = new ArrayList<>();
        MonsterInMap monsterInMap;
        for (MapTemplate.MonsterData monster : mapTemplate.getMonsters()) {
            monsterInMap = new MonsterInMap();
            monsterInMap.setPercents(monster.getPercents());
            monsterInMap.setLevelMin(monster.getLevelMin());
            monsterInMap.setLevelMax(monster.getLevelMax());
            monsterInMap.setMonsterTemplate(MonsterFactory.getById(monster.getMonsterId()));
            result.add(monsterInMap);
        }
        return result;
    }


    public static void main(String[] args) {
        for (MapTemplate mapTemplate : mapTemplates) {
            System.out.println(JSON.toJSONString(mapTemplate));
        }
    }

}
